/*
管理员相关路由
*/

// 创建路由器
const express = require("express");
//引入连接池
const pool = require("../../pool");
//定义路由器
const router = express.Router();
//抛出路由器
module.exports = router;

/*
 *API:GET /admin/login
 *请求数据:/login/:aname/:apwd'
 *完成用户登录验证
 *返回数据
 *{code:200,msg:'login success!'}
 *{code:400,msg:'aname of apwd err!'}
 */

router.get("/login/:aname/:apwd", (req, res) => {
  let aname = req.params.aname;
  let apwd = req.params.apwd;
  //因为管理员密码被加密过 所以 接受用户返回的数据也要加密一次 才可以对应查找
  pool.query("SELECT aid FROM xfn_admin WHERE aname=? AND apwd=PASSWORD(?)", [aname, apwd], (err, result) => {
    if (err) throw err;
    if (result.length > 0) {
      res.send({ code: 200, msg: "login success!" });
    } else {
      res.send({ code: 400, msg: "aname of apwd err!" });
    }
  });
});

/*
*API:PATCH /admin
*请求数据:{aname:'xxx',oldpwd:'xxx',newapwd:'xxx'}
*根据管理员名和密码修改管理员密码  
*返回数据
*{code:200,msg:'update success!'}
*{code:400,msg:'aname of apwd err!'}
*{code:400,msg:'oldawpd not update!'}
修改部分数据用PATCH  修改全部数据用PUT
*/

router.patch("/admin", (req, res) => {
  let data = req.body;
  console.log(data);
  //因为管理员密码被加密过 所以 接受用户返回的数据也要加密一次 才可以对应查找
  //先验证传入的aname和oldpswd 是否正确
  pool.query("SELECT aid FROM xfn_admin WHERE aname=? AND apwd=PASSWORD(?)", [data.aname, data.oldPwd], (err, result) => {
    if (err) throw err;
    //如果查询结果==0说明根据用户名和密码错误
    if (result.length == 0) {
      res.send({ code: 400, msg: "password err" });
      return;
    }
    //如果查询到了用户则修改密码
    pool.query("UPDATE xfn_admin SET apwd=PASSWORD(?) WHERE aname=?", [data.newPwd, data.aname], (err, result) => {
      if (err) throw err;
      if (result.changedRows > 0) {
        //说明修改成功
        res.send({ code: 200, msg: "updated success!" });
      } else {
        res.send({ code: 401, msg: "pwd not updated" });
      }
    });
  });
});
